import numpy as np
import pandas as pd

def classify(inputTree, featLabels, testVec):
    firstStr = list(inputTree.keys())[0]  # 根结点 key
    firstLabel = firstStr[:]
    secondDict = inputTree[firstStr]  # 剩下的值

    if '<=' in firstStr:  # 连续型特征在模型保存时key变了
        firstStr = firstStr.split('<=')[0]  # 得到对应标签，需要拆开

    featIndex = featLabels.index(firstStr)
    for key in secondDict.keys():
        # 离散型特征
        if type(testVec[featIndex]).__name__ == 'str':
            if testVec[featIndex] == key:
                if type(secondDict[key]).__name__ == 'dict':  # 字典，递归继续往下走
                    classLable = classify(secondDict[key], featLabels, testVec)
                else:  # 叶子结点，返回结果
                    classLable = secondDict[key]
        # 连续型特征
        else:
            value = float(firstLabel.split('<=')[1])
            if testVec[featIndex] > value:  # 大于判断条件，特征对应的特征值为否 {'密度<=0.381': {'否': '好瓜', '是': '坏瓜'}
                if type(secondDict['否']).__name__ == 'dict':
                    classLable = classify(secondDict['否'], featLabels, testVec)
                else:
                    classLable = secondDict['否']
            else:
                if type(secondDict['是']).__name__ == 'dict':
                    classLable = classify(secondDict['是'], featLabels, testVec)
                else:
                    classLable = secondDict['是']
    return classLable

data1 = pd.read_csv('../wine.csv', sep=',')
label = ["type","Alcohol","Malic acid","Ash","Alcalinity of ash"  ,"Magnesium","Total phenols","Flavanoids","Nonflavanoid phenols","Proanthocyanins","Color intensity","Hue","OD280/OD315 of diluted wines","Proline" ]
data1.columns = label
# 这里输入的标签不能有type
in_label = ["Alcohol","Malic acid","Ash","Alcalinity of ash"  ,"Magnesium","Total phenols","Flavanoids","Nonflavanoid phenols","Proanthocyanins","Color intensity","Hue","OD280/OD315 of diluted wines","Proline" ]
Features1 = data1.iloc[100:131,1:14]
target1 = data1.iloc[100:131,0]
tree = {'Proline<=750.0': {'否': {'Color intensity<=3.435': {'否': 1.0, '是': 2.0}}, '是': {'Alcohol<=13.175': {'否': {'Alcohol<=13.24': {'否': 2.0, '是': 1.0}}, '是': 2.0}}}}
right=0
for x,y in zip(Features1.values,target1):
    r = classify(tree,in_label,x)
    if r == y:
        right=right+1
print("准确率：",right/len(target1))